const sqlite3 = require('sqlite3');
const path    = require('path');
const db_name = path.join(__dirname, 'data.db');

const db = new sqlite3.Database(db_name, err => {
    if(err){
        console.log(err);
        reject(err);
    }
});

async function findData(){
    return new Promise((resolve ,reject) => {
        const query_sql = `
        SELECT id, user_name, age FROM user
        `;

        db.all(query_sql, (err, rows) => {
            if(err){
                console.log(err);
                reject(err);
            }
            else{
                console.log('qurey successfully!');
                resolve(rows);
            }
        });
    });
}

let insertData = function(data){
    return new Promise((resolve, reject) => {
        const insert_sql = `
        INSERT INTO user (id, user_name, age)
        VALUES (?, ?, ?)
        `;

        db.run(insert_sql, [Number(data.id), data.user_name,
            Number(data.age)], err=> {
            if(err){
                console.log(err);
                reject(err);
            }else{
                resolve(true);
            }
        })
    })
}

module.exports = {findData, insertData}
